package com.itheima.transaction;

import org.aopalliance.intercept.Joinpoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author huyoufu <https://github.com/huyoufu>
 * @TIME 2020-08-09 11:46
 * @description 专为事务控制 aop编程
 */

@Component
@Aspect
public class TransactionAspect {
    @Autowired
    private TransactionManager transactionManager;
    @Around("execution( * com.itheima.service..*.*(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result=null;
        try {
            //开启事务
            transactionManager.begin();


            //调用原来业务service代码
            result = joinPoint.proceed();


            //提交事务
            transactionManager.commit();
        }catch (Throwable e){
            //回滚事务
            transactionManager.rollback();

            //异常处理
            throw e;
        }finally {
            //关闭资源
            transactionManager.close();
        }
        return result;
    }

}
